import { reviewTopic } from '~/server/database/services/topicService'
import { ReviewStatus } from '~/server/database/models/Topic'

export default defineEventHandler(async (event) => {
  try {
    const id = getRouterParam(event, 'id')
    const body = await readBody(event)
    
    if (!id || isNaN(parseInt(id))) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的题目ID'
      })
    }

    const { reviewStatus, reviewReason } = body

    // 验证审核状态
    if (!reviewStatus || !Object.values(ReviewStatus).includes(reviewStatus)) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的审核状态'
      })
    }

    // 审核题目
    const topic = await reviewTopic(parseInt(id), reviewStatus, reviewReason)

    if (!topic) {
      throw createError({
        statusCode: 404,
        statusMessage: '题目不存在'
      })
    }

    return {
      success: true,
      data: topic,
      message: '题目审核完成'
    }
  } catch (error: unknown) {
    console.error('审核题目失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: '审核题目失败'
    })
  }
})
